package net.oschina.jhssm.module.system.controller;

import net.oschina.jhssm.common.annotation.RequireLog;
import net.oschina.jhssm.common.controller.BaseController;
import net.oschina.jhssm.common.entity.R;
import net.oschina.jhssm.common.exception.BusinessException;
import net.oschina.jhssm.module.system.entity.SysUser;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;

/**
 * Created by zhaojb on 2017/8/19.
 */
@Controller
public class LoginController extends BaseController{

    @RequestMapping(value = "", method = RequestMethod.GET)
    public String index() {
        return "main";
    }

    @RequestMapping(value = "login", method = RequestMethod.GET)
    public String login() {
        return "login";
    }

    @RequestMapping(value = "login", method = RequestMethod.POST)
    @ResponseBody
    @RequireLog(value = "用户登录")
    public R login(@Valid SysUser user, BindingResult result) {
        checkBindingResult(result);
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
        try {
            subject.login(token);
        } catch (UnknownAccountException e) {
            throw new BusinessException("用户名/密码错误");
        } catch (IncorrectCredentialsException e) {
            throw new BusinessException("用户名/密码错误");
        }
        return R.ok();
    }

    @RequestMapping(value = "logout", method = RequestMethod.GET)
    @RequireLog(value = "登出")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:/";
    }

}
